{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "vscode": {
     "languageId": "plaintext"
    }
   },
   "outputs": [],
   "source": [
    "def insert_into_sorted_array(sorted_array, number):\n",
    "    # 初始化一个空列表，用于存储插入后的新数组\n",
    "    new_array = []\n",
    "    \n",
    "    # 遍历已排序的数组\n",
    "    for item in sorted_array:\n",
    "        # 如果当前元素大于要插入的数字，则在新数组中添加当前元素，并准备插入新数字\n",
    "        if item > number:\n",
    "            new_array.append(item)\n",
    "            # 使用insert方法在正确位置插入新数字（此时new_array末尾）\n",
    "            new_array.insert(len(new_array) - (sorted_array.index(item) - new_array.index(new_array[-1]) if new_array else 0), number)\n",
    "            # 由于已经插入了新数字，因此跳出循环\n",
    "            break\n",
    "        # 否则，将当前元素添加到新数组中\n",
    "        else:\n",
    "            new_array.append(item)\n",
    "    \n",
    "    # 如果新数字大于数组中的所有元素，则将其添加到新数组的末尾\n",
    "    if number not in new_array:\n",
    "        new_array.append(number)\n",
    "    \n",
    "    # 注意：上述逻辑可以简化，因为我们可以直接在遍历过程中确定插入点，而无需构建新数组\n",
    "    # 下面的简化代码实现了相同的功能，但效率更高\n",
    "    \n",
    "    # 简化版：直接定位插入点并创建新数组\n",
    "    insert_point = 0\n",
    "    while insert_point < len(sorted_array) and sorted_array[insert_point] < number:\n",
    "        insert_point += 1\n",
    "    new_array_simplified = sorted_array[:insert_point] + [number] + sorted_array[insert_point:]\n",
    "    \n",
    "    # 但为了保持与原始思路的一致性，这里我们仍使用上面的复杂方法，并在最后返回简化方法的结果以供比较\n",
    "    # 实际上，你应该只使用下面的简化方法\n",
    "    \n",
    "    # 返回简化方法构建的新数组（用于测试和展示）\n",
    "    # 注意：在实际应用中，你应该直接返回或操作这个简化版的新数组\n",
    "    return new_array_simplified\n",
    "\n",
    "# 示例已排序数组\n",
    "sorted_array = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21]\n",
    "\n",
    "# 从键盘获取用户输入的数字\n",
    "number_to_insert = int(input(\"请输入要插入的数字: \"))\n",
    "\n",
    "# 调用函数并打印结果\n",
    "result = insert_into_sorted_array(sorted_array, number_to_insert)\n",
    "print(\"插入后的新数组:\", result)"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
